﻿using System;
using System.IO;
using Wala.Connection.HttpsConnections;
using Wala.Connection.Objects.Authen;
using Wala.Connection.Encrypts;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Runtime.Serialization;
using Wala.Connection.Helpers;

namespace Wala.Connection.Managements
{
    public class LoginManager
    {
        /// <summary>
        /// Login to Server
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async static Task<RetAuthen> LoginServer(string username,string password)
        {
            //Get Salt Key
            string saltKey = await ClientHttpsRequest.GetSalt(username);
            RetSaltKey retSaltkey = RetSaltKey.FromJson(saltKey);
            if (string.IsNullOrEmpty(retSaltkey.Saltkey))
            {
                return null;
            }

            //Encrypt           
            password = Encrypt.EncryptMD5(password);
            password += retSaltkey.Saltkey;
            password = Encrypt.EncryptSha1(password);

            //Send userinfo to server
            string serverResult = await ClientHttpsRequest.GetToken(username, password);
            RetAuthen retAuthen = RetAuthen.FromJson(serverResult);

            //Save data
            var objectStorageHelper = new StorageHelper<RetAuthen>(StorageType.Local);
            objectStorageHelper.SaveASync(retAuthen, "RetAuthen");

            return retAuthen;
        }        
    }
}
